package com.onluy.framework.system.interceptor;

import java.io.IOException;  
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; 
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;  
import com.alibaba.fastjson.JSONArray; 
import com.onluy.framework.system.annotation.ParamCheck; 
import com.onluy.mvc.app.JsonResult; 

/**
 * 参数校验器拦截
 *
 */
public class ParamCheckInterceptor extends HandlerInterceptorAdapter{
    protected Logger log; 
 
    
	public ParamCheckInterceptor()
    {
        log = LoggerFactory.getLogger(getClass()); 
    }
  
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
        throws Exception
    { 
        super.postHandle(request, response, handler, modelAndView); 
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
        throws Exception
    {
    	 super.afterCompletion(request, response, handler, ex);
    }
     

	/**
	 * 参数校验器拦截
	 * 
	 */
	@SuppressWarnings("deprecation") 
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if(handler instanceof HandlerMethod){
			HandlerMethod method = (HandlerMethod)handler;
	    	//获取方法指定的校验参数注解
			ParamCheck paramCheck = method.getMethodAnnotation(ParamCheck.class); 
 
			log.info("====================paramCheck start" ); 
	    	//2、指定需要校验的参数
	    	if(!StringUtils.isEmpty(paramCheck) && paramCheck.value().length > 0 && !"".equals(paramCheck.value()[0])){
	    		String[] paras = paramCheck.value();
	    		for (String para : paras) {
	    			String[] ckstr=para.trim().split(":");
	    			String name=ckstr[0];
	    			String text=name;
	    			if(ckstr.length>1) {
	    				text=ckstr[1];
	    			}
	    			
	    			String paraValue = request.getParameter(name);
	    			
	    			//不能为空
					if(StringUtils.isEmpty(paraValue)){
						writerRespInfo(response, false, text + "不能为空！");
			    		return false;
					} 
					 
				}
	    	}

			log.info("====================paramCheck end"); 
	    	
	    }
	    return true;
	}
	
	/**
	 * 向浏览器写返回信息
	 * 
	 * @param respCode
	 * @param respDesc
	 * @return
	 * @throws IOException 
	 */
	@SuppressWarnings("unchecked")
	private void writerRespInfo(HttpServletResponse response, Boolean success, String respDesc) throws IOException{
		JsonResult respInfo = new JsonResult();
		respInfo.setSuccess(success);;
		respInfo.setMsg( respDesc);
		
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().write(JSONArray.toJSONString(respInfo));
	}	
}
